/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.gov.cemaden.smp.util;

import com.sun.tools.attach.VirtualMachine;
import java.io.File;
import javax.management.remote.JMXServiceURL;

/**
 *
 * @author Simone Santos
 */
public class JVMRuntimeClient {

    private static final String CONNECTOR_ADDRESS = "com.sun.management.jmxremote.localConnectorAddress";
    private final JMXServiceURL jmxURL;

    public JVMRuntimeClient(String pid) {
        jmxURL = getURLForPid(pid);
    }

    // JMXServiceURL O endereço de um servidor de conector API JMX, o endereço é um serviço de URL
    public final JMXServiceURL getJMXServiceURL() {
        return jmxURL;
    }

    private JMXServiceURL getURLForPid(String pid) {
        try {
            final VirtualMachine vm = VirtualMachine.attach(pid);

            // get the connector address
            String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
            // no connector address, so we start the JMX agent
            if (connectorAddress == null) {
                //contruir caminho para agente de gestão
                String agent = vm.getSystemProperties().getProperty("java.home")
                        + File.separator + "lib" + File.separator + "management-agent.jar";
                // agente de carga em alvo VM
                vm.loadAgent(agent);
                // agent is started, get the connector address
                connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
                assert connectorAddress != null;
            }
            return new JMXServiceURL(connectorAddress);
        } catch (Exception x) {
            throwSyntaxError("cannot attach to target vm " + pid + ": " + x);
        }
        return null;
    }

    private void throwSyntaxError(String msg) {
        System.err.println(msg);
        throw new IllegalArgumentException(msg);
    }
}
